package com.eduagent.xwqeduagent.api.machineTranslation;

import com.eduagent.xwqeduagent.api.machineTranslation.model.TranslationRequest;
import com.eduagent.xwqeduagent.api.machineTranslation.model.TranslationResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 讯飞机器翻译客户端
 */
@Slf4j
public class TranslationClient {

    private static final String API_URL = "https://itrans.xfyun.cn/v2/its";
    private static final String HOST = "itrans.xfyun.cn";
    private static final String HTTP_METHOD = "POST";
    private static final String HTTP_PROTO = "HTTP/1.1";
    private static final String REQUEST_LINE = HTTP_METHOD + " /v2/its " + HTTP_PROTO;
    private static final String ALGORITHM = "hmac-sha256";
    private static final String CONTENT_TYPE = "application/json";

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final String apiKey;
    private final String apiSecret;
    private final String appId;

    public TranslationClient(String apiKey, String apiSecret, String appId) {
        this.apiKey = apiKey;
        this.apiSecret = apiSecret;
        this.appId = appId;
    }

    /**
     * 执行翻译请求
     *
     * @param sourceText 源文本
     * @param fromLang   源语言
     * @param toLang     目标语言
     * @return 翻译结果
     */
    public TranslationResponse translate(String sourceText, String fromLang, String toLang) {
        try {
            // 构建请求对象
            TranslationRequest request = buildRequest(sourceText, fromLang, toLang);
            
            // 将请求对象转换为JSON
            String requestJson = objectMapper.writeValueAsString(request);
            
            // 发送请求
            String responseJson = sendRequest(requestJson);
            
            // 解析响应
            TranslationResponse response = objectMapper.readValue(responseJson, TranslationResponse.class);
            
            return response;
        } catch (Exception e) {
            log.error("Translation failed", e);
            TranslationResponse errorResponse = new TranslationResponse();
            errorResponse.setCode(-1);
            errorResponse.setMessage("Translation failed: " + e.getMessage());
            return errorResponse;
        }
    }

    /**
     * 构建翻译请求对象
     */
    private TranslationRequest buildRequest(String sourceText, String fromLang, String toLang) {
        TranslationRequest request = new TranslationRequest();
        
        // 设置公共参数
        TranslationRequest.Common common = new TranslationRequest.Common();
        common.setAppId(appId);
        request.setCommon(common);
        
        // 设置业务参数
        TranslationRequest.Business business = new TranslationRequest.Business();
        business.setFrom(fromLang);
        business.setTo(toLang);
        request.setBusiness(business);
        
        // 设置文本数据（Base64编码）
        TranslationRequest.TranslationData data = new TranslationRequest.TranslationData();
        data.setText(Base64.encodeBase64String(sourceText.getBytes(StandardCharsets.UTF_8)));
        request.setData(data);
        
        return request;
    }

    /**
     * 发送翻译请求
     */
    private String sendRequest(String requestJson) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(API_URL);
            
            // 设置请求头
            String date = getGMTDate();
            String digest = getDigest(requestJson);
            String authorization = getAuthorization(date, digest);
            
            post.setHeader("Content-Type", CONTENT_TYPE);
            post.setHeader("Accept", "application/json,version=1.0");
            post.setHeader("Host", HOST);
            post.setHeader("Date", date);
            post.setHeader("Digest", digest);
            post.setHeader("Authorization", authorization);
            
            // 设置请求体
            post.setEntity(new StringEntity(requestJson, StandardCharsets.UTF_8));
            
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(post);
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.error("Translation API error: status={}, response={}", statusCode, responseBody);
            }
            
            return responseBody;
        }
    }

    /**
     * 获取GMT格式的当前日期
     */
    private String getGMTDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(new Date());
    }

    /**
     * 计算请求体的摘要
     */
    private String getDigest(String bodyStr) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] hash = messageDigest.digest(bodyStr.getBytes(StandardCharsets.UTF_8));
        return "SHA-256=" + Base64.encodeBase64String(hash);
    }

    /**
     * 生成签名
     */
    private String generateSignature(String date, String digest) throws NoSuchAlgorithmException, InvalidKeyException {
        String signatureOrigin = "host: " + HOST + "\n" +
                "date: " + date + "\n" +
                REQUEST_LINE + "\n" +
                "digest: " + digest;
        
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        hmacSha256.init(secretKey);
        byte[] signatureSha = hmacSha256.doFinal(signatureOrigin.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(signatureSha);
    }

    /**
     * 构建Authorization头
     */
    private String getAuthorization(String date, String digest) throws NoSuchAlgorithmException, InvalidKeyException {
        String signature = generateSignature(date, digest);
        return String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"host date request-line digest\", signature=\"%s\"",
                apiKey, ALGORITHM, signature);
    }
} 